package com.Cychat.post.service.impl;


import com.Cychat.commons.entity.pojo.Favorite;
import com.Cychat.commons.entity.pojo.Post;
import com.Cychat.post.entity.dto.FavoriteDTO;
import com.Cychat.post.entity.mq.CollectMonitor;
import com.Cychat.post.mapper.FavoriteMapper;
import com.Cychat.post.mapper.PostMapper;
import com.Cychat.post.service.FavoriteService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public List<FavoriteDTO> selectPostFavorites(Long userId) {
        return favoriteMapper.selectPostFavorites(userId);
    }

    @Override
    public void addFavorite(Long userId, Integer postId) {
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setTargetId(postId);
        favorite.setType("post");
        favorite.setCreateTime(new Date());
        favoriteMapper.insert(favorite);
        if (postId != null) { // 避免空指针，确保帖子ID存在
            LambdaUpdateWrapper<Post> lambdaWrapper = new LambdaUpdateWrapper<>();
            lambdaWrapper.eq(Post::getPostId, postId) // 条件：匹配帖子ID
                    .setSql("favorite_count = favorite_count + 1"); // 自增逻辑
            postMapper.update(null, lambdaWrapper); // 执行更新
        }
        CollectMonitor monitor = new CollectMonitor( userId, postId);
        rabbitTemplate.convertAndSend("cychat.exchange","collect",monitor);
    }

    @Override
    public void deleteFavorite(Long userId, Integer postId) {
        favoriteMapper.deleteFavorite(userId, postId);
        if (postId != null) { // 避免空指针，确保帖子ID存在
            LambdaUpdateWrapper<Post> lambdaWrapper = new LambdaUpdateWrapper<>();
            lambdaWrapper.eq(Post::getPostId, postId) // 条件：匹配帖子ID
                    .setSql("favorite_count = favorite_count - 1"); // 自增逻辑
            postMapper.update(null, lambdaWrapper); // 执行更新
        }
    }

    @Override
    public boolean isFavorite(Integer postId, Long userId) {
        Favorite favorite = favoriteMapper.selectOne(new LambdaUpdateWrapper<Favorite>()
                .eq(Favorite::getTargetId, postId)
                .eq(Favorite::getUserId, userId)
                .eq(Favorite::getType, "post"));
        if (favorite != null) {
            return true;
        }
        return false;
    }

}
